﻿// (c) Copyright Fernando Cerqueira.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.Win32;
using AppRes = WindowsPhoneCommands.Resources;

// ReSharper disable CheckNamespace
namespace WindowsPhoneCommands
// ReSharper restore CheckNamespace
{
    /// <summary>
    /// Interaction logic for XapDeploy.xaml
    /// </summary>
    // ReSharper disable RedundantExtendsListEntry
    public partial class XapDeployDialog : DialogWindow
    // ReSharper restore RedundantExtendsListEntry
    {

        #region fields

        private XapFile _xap;
        internal MainControl ParentWindow;

        #endregion

        #region constructor / closed

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            ParentWindow = null;
            _xap = null;
        }

        public XapDeployDialog()
        {
            InitializeComponent();
            Background = VsTheming.GetDialogBackground();
            Foreground = VsTheming.GetWindowText();
        }

        #endregion

        #region events callback

        private void BtnBrowseClick(object sender, RoutedEventArgs e)
        {
            var ofd = new OpenFileDialog
            {
                Filter = "Xap File (*.xap)|*.xap",
                CheckFileExists = true,
                Multiselect = false,
                ValidateNames = true,
                Title = "Select Xap file"
            };
            if (ofd.ShowDialog() == true)
            {
                Xapfilename.Text = ofd.FileName;
            }
        }

        private void XapfilenameTextChanged(object sender, TextChangedEventArgs e)
        {
            var filename = Xapfilename.Text.Trim();
            if (string.IsNullOrEmpty(filename))
            {
                return;
            }
            if (!System.IO.File.Exists(filename))
            {
                MessageBox.Show(AppRes.FileNotExist, AppRes.ToolWindowTitle);
                Clearxap();
                return;
            }
            if (!ParentWindow.Package.PhoneDevice.Connected)
            {
                Clearxap();
                MessageBox.Show(AppRes.ConnectionLost, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            try
            {
                _xap = new XapFile(filename);
                if (ParentWindow.Package.PhoneDevice.IsApplicationInstalled(new Guid(_xap.Guid)))
                {
                    BntUpdDeploy.IsEnabled = true;
                }
                BntNewDeploy.IsEnabled = true;
                expanappdata.IsEnabled = true;
                ProductIdxap.Text = _xap.Guid;
                Titlexap.Text = _xap.Title;
                Versionxap.Text = _xap.Version;
                Authorxap.Text = _xap.Author;
                Genrexap.Text = _xap.Genre;
                expanappdata.IsExpanded = true;
            }
            catch (Exception ex)
            {
                Clearxap();
                MessageBox.Show(AppRes.LaunchError + ex.Message, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void BntNewDeployClick(object sender, RoutedEventArgs e)
        {
            if (!ParentWindow.Package.PhoneDevice.Connect())
            {
                Clearxap();
                MessageBox.Show(AppRes.ConnectionLost, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            var filename = Xapfilename.Text.Trim();
            var oldcur = Cursor;
            Cursor = Cursors.Wait;
            try
            {
                if (ParentWindow.Package.PhoneDevice.IsApplicationInstalled(new Guid(_xap.Guid)))
                {
                    ParentWindow.Package.PhoneDevice.TerminateRunningInstances(_xap.Guid);
                    ParentWindow.Package.PhoneDevice.Uninstall(_xap.Guid);
                }

                ParentWindow.Package.PhoneDevice.InstallApplication(new Guid(_xap.Guid), Guid.Empty, _xap.Genre, _xap.Icon, filename);
                // ReSharper disable PossibleInvalidOperationException
                if (Chklaunch.IsChecked.Value)
                // ReSharper restore PossibleInvalidOperationException
                {
                    ParentWindow.Package.PhoneDevice.Launch(_xap.Guid);
                }
                EnvPhoneDevice.UpdateCacheApp(_xap.Title, _xap.Title, _xap.Guid);
                ParentWindow.LoadTreeViewDevice();
            }
            catch (OutOfMemoryException ex)
            {
                Cursor = oldcur;
                MessageBox.Show(AppRes.OutOfMemoryDevice + ex.Message);
            }
            catch (Exception ex)
            {
                Cursor = oldcur;
                MessageBox.Show(AppRes.DeployError + ex.Message, AppRes.ToolWindowTitle);
            }
            Clearxap();
            Cursor = oldcur;
        }

        private void BntUpdDeployClick(object sender, RoutedEventArgs e)
        {
            if (!ParentWindow.Package.PhoneDevice.Connected)
            {
                Clearxap();
                MessageBox.Show(AppRes.ConnectionLost, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            var filename = Xapfilename.Text.Trim();
            var oldcur = Cursor;
            Cursor = Cursors.Wait;
            try
            {
                ParentWindow.Package.PhoneDevice.TerminateRunningInstances(_xap.Guid);
                ParentWindow.Package.PhoneDevice.UpdateApplication(_xap.Guid,_xap.Genre, _xap.Icon, filename);
                // ReSharper disable PossibleInvalidOperationException
                if (Chklaunch.IsChecked.Value)
                // ReSharper restore PossibleInvalidOperationException
                {
                    ParentWindow.Package.PhoneDevice.Launch(_xap.Guid);
                }
                EnvPhoneDevice.UpdateCacheApp(_xap.Title, _xap.Title, _xap.Guid);
                ParentWindow.LoadTreeViewDevice();
            }
            catch (OutOfMemoryException ex)
            {
                Cursor = oldcur;
                MessageBox.Show(AppRes.OutOfMemoryDevice + ex.Message);
            }
            catch (Exception ex)
            {
                Cursor = oldcur;
                MessageBox.Show(AppRes.DeployError + ex.Message, AppRes.ToolWindowTitle);
            }
            Clearxap();
            Cursor = oldcur;
        }

        private void BntCacheClick(object sender, RoutedEventArgs e)
        {
            var oldcur = Cursor;
            Cursor = Cursors.Wait;
            var inifolder = Common.FolderData();
            System.Diagnostics.Process.Start("explorer.exe", inifolder);
            Cursor = oldcur;
        }

        #endregion

        #region private methods

        private void Clearxap()
        {
            Xapfilename.Text = string.Empty;
            expanappdata.IsExpanded = false;
            expanappdata.IsEnabled = false;
            BntNewDeploy.IsEnabled = false;
            BntUpdDeploy.IsEnabled = false;
        }

        #endregion
    }
}
